﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebTest
{
    /// <summary>
    /// 输入值与给定值必须不同
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class NotDefaultValueAttribute : ValidationAttribute, IClientValidatable
    {
        public string InputString { get; set; }
        public NotDefaultValueAttribute()
        {
            ErrorMessage = "请选其中一项";
        }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule
            {
                ValidationType = "notdefaultvalue",
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
            };
            rule.ValidationParameters["inputstring"] = InputString;

            yield return rule;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
                return true;
            string inputString = (string)value;
            if (inputString.Contains(InputString))
            {
                return false;
            }
            return true;
        }
    }
    /// <summary>
    /// 输入值必须包含给定值
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class DefaultValueAttribute : ValidationAttribute, IClientValidatable
    {
        public string InputString { get; set; }
        public DefaultValueAttribute()
        {
            ErrorMessage = "必须和默认值相同";
        }
        public override bool IsValid(object value)
        {
            string inputString = (string)value;
            if (inputString.Contains(InputString))
                return true;

            return false;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule
            {
                ValidationType = "defaultvalue",
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
            };
            rule.ValidationParameters["inputstring"] = InputString;
            yield return rule;
        }
    }
}


